<?php

/**
 * This is the model class for table "project_image".
 *
 * The followings are the available columns in table 'project_image':
 * @property string $id
 * @property string $image
 * @property string $project
 */
class ProjectImage extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @return ProjectImage the static model class
	 */
        public  $image_obj;
        public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'project_image';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('project', 'required'),
			array('image', 'length', 'max'=>255),
                        array('image', 'file', 'allowEmpty' => true,
                            'types' => 'jpg, gif, png, jpeg',
                            'maxSize' => 1024 * 1024 * 10, // 10MB
                            'tooLarge' => 'The file was larger than 10MB. Please upload a smaller file.',
                        ),
                        array('project', 'numerical', 'integerOnly' => true),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, image, project', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}
        public function getThumb(){
            if ($this->image != null) {
                $image_parts = pathinfo($this->image);
                return Yii::app()->baseUrl . '/' . $image_parts["dirname"] . '/' . $image_parts["filename"] . '_thumb.' . $image_parts["extension"];
            } else {
                return Yii::app()->baseUrl.'/images/no_image.jpg';
            }
        }
        public function beforeDelete(){
            if ($this->image != null) {
                $path_parts = pathinfo($this->image);
                $pos = strrpos($path_parts["basename"], ".");
                $ext = substr($path_parts["basename"], $pos);
                $file_name = str_replace($ext, '', $path_parts["basename"]);
                $thumb_path = $path_parts["dirname"] . '/' . $file_name . '_thumb.' . $path_parts["extension"];
                if (file_exists($thumb_path)) {
                    unlink($thumb_path);
                }
                if (file_exists($this->image)) {
                    unlink($this->image);
                }
            }
            return true;
        }
        public function beforeSave(){
            $today = getdate();
            $month = $today['mon'];
            $day = $today['mday'];
            $year = $today['year'];
            $upload_path = Yii::app()->params['media_dir'] . '/' . $year . '/' . $month . '/' . $day . '/';
            $upload_name = md5($this->image_obj->name).time();
            $image_path = $upload_path . $upload_name . '.' . $this->image_obj->extensionName;
            $this->image = $image_path;
            if (!file_exists($upload_path)) {
                if (!Tool::mkpath($upload_path)) {
                    echo('Make directory error');
                    exit;
                }
            }
            $this->image_obj->saveAs($this->image);

            $path_parts = pathinfo($this->image);
            $pos = strrpos($path_parts["basename"], ".");
            $ext = substr($path_parts["basename"], $pos);
            $file_name = str_replace($ext, '', $path_parts["basename"]);
            $thumb = $path_parts["dirname"] . '/' . $file_name . '_thumb.' . $path_parts["extension"];
            ImageHelper::thumb(Yii::app()->params['thumb_width'], Yii::app()->params['thumb_height'], $this->image, array(
                        'method' => 'adaptiveResize',
                        'quality' => 90), $thumb
            );
            ImageHelper::thumb(Yii::app()->params['image_width'], Yii::app()->params['image_height'], $this->image, array(
                        'method' => 'adaptiveResize',
                        'quality' => 90), $this->image
            );
            return true;
        }
	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'image' => 'Image',
			'project' => 'Project',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id,true);
		$criteria->compare('image',$this->image,true);
		$criteria->compare('project',$this->project,true);

		return new CActiveDataProvider(get_class($this), array(
			'criteria'=>$criteria,
		));
	}
}